#include "GW_RelayControl.h"

GW_RelayControl::GW_RelayControl()
{
   this->isAction = false;
   this->time = 0;
   this->relay = 0;
   this->timeout = 10;
   this->mode = RELAYMODE_AUTO;
   this->CTLGPIO = NULL;
   this->CTLPin = NULL;
}

void  GW_RelayControl::setTimeOut(int time)
{
   if (time>0)
   {
      this->mode = RELAYMODE_PULSE;
      this->timeout = time;
   }
   else
   {
      this->mode = RELAYMODE_AUTO;
   }
}

void  GW_RelayControl::resetTime()
{
   this->time = 0;
}

void  GW_RelayControl::setCTLPin(GPIO_TypeDef *CTLGPIO, uint16_t CTLPin, GPIO_PinState activeEdge)
{
   this->CTLGPIO = CTLGPIO;
   this->CTLPin = CTLPin;
   this->activeEdge = activeEdge;
}

void GW_RelayControl::active()
{
   if (!this->isAction)
   {
      if (this->CTLPin != NULL)
      {
         HAL_GPIO_WritePin(this->CTLGPIO, this->CTLPin, this->activeEdge);
      }
   }
   this->isAction = true;
   this->time = 0;
}

void GW_RelayControl::unactive()
{
   GPIO_PinState pin;
   if (this->isAction)
   {
      if (this->CTLPin != NULL)
      {
         if (this->activeEdge == GPIO_PIN_RESET)
         {
            pin = GPIO_PIN_SET;
         }
         else
            pin = GPIO_PIN_RESET;
         HAL_GPIO_WritePin(this->CTLGPIO, this->CTLPin, pin);
      }
   }
   this->isAction = false;
}

void  GW_RelayControl::Tick(int second)
{
   if (this->isAction && (this->mode == RELAYMODE_PULSE))
   {
      this->time += second;
      if (this->time >= this->timeout)
      {
         HAL_GPIO_TogglePin(this->CTLGPIO, this->CTLPin);
         this->isAction = false;
         this->time = 0;
      }
   }
}

//void  GW_RelayControl::setRelay(bool enable) //设置
//{
//   if (enable) *(this->mark) = 1;
//   else *(this->mark) = 0;
//}

void  GW_RelayControl::enableRelay(int chid)
{
   u32 tmp=0;
   if (this->mark!=NULL)
   {
      tmp = (1 << chid);
      *(this->mark) = *(this->mark) | tmp;
   }
}

void  GW_RelayControl::disableRelay(int chid)
{
   u32 tmp=0;
   if (this->mark!=NULL)
   {
      tmp = (1 << chid);
      *(this->mark) = *(this->mark) & ~tmp;
   }
}

void  GW_RelayControl::setMark(u32 *mark)
{
   this->mark = mark;
}

